package org.jflame.captcha.creator;

import org.jflame.captcha.Captcha;
import org.jflame.captcha.validator.SingleVerifiable;
import org.jflame.commons.util.ChineseHelper;
import org.jflame.commons.util.StringHelper;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.RandomUtils;

/**
 * 文本验证码生成器
 * 
 * @author charles.zhang
 */
public class TextCaptchaCreator extends AbstractTextCaptchaCreator<String> {

    private boolean hasChinese = false;
    private boolean hasNumber = true;
    private boolean hasLetter = true;
    private int count = 4;

    public TextCaptchaCreator() {
    }

    public TextCaptchaCreator(boolean hasChinese, boolean hasNumber, boolean hasLetter) {
        this(hasChinese, hasNumber, hasLetter, 0);
    }

    public TextCaptchaCreator(boolean hasChinese, boolean hasNumber, boolean hasLetter, Integer count) {
        this.hasChinese = hasChinese;
        this.hasNumber = hasNumber;
        this.hasLetter = hasLetter;
        if (!hasLetter && !hasNumber && !hasLetter) {
            throw new IllegalArgumentException();
        }
        if (count != null && count > 0) {
            this.count = count;
        }
    }

    @Override
    public Captcha<SingleVerifiable<String>,String> create() {
        String randomStr;
        if (hasChinese) {
            if (!hasLetter && !hasNumber) {
                randomStr = ChineseHelper.randomChinese(count);
            } else {
                randomStr = RandomStringUtils.random(count - 1, hasLetter, hasNumber);
                randomStr = StringHelper.insertAt(randomStr, ChineseHelper.randomChinese(1),
                        RandomUtils.nextInt(0, count - 1));
            }
        } else {
            randomStr = RandomStringUtils.random(count, hasLetter, hasNumber);
        }
        return new Captcha<SingleVerifiable<String>,String>(new SingleVerifiable<String>(randomStr), randomStr);
    }

    @Override
    public SingleVerifiable<String> parse(String verifiableString) {
        return new SingleVerifiable<String>(verifiableString);
    }

    public boolean isHasChinese() {
        return hasChinese;
    }

    public void setHasChinese(boolean hasChinese) {
        this.hasChinese = hasChinese;
    }

    public boolean isHasNumber() {
        return hasNumber;
    }

    public void setHasNumber(boolean hasNumber) {
        this.hasNumber = hasNumber;
    }

    public boolean isHasLetter() {
        return hasLetter;
    }

    public void setHasLetter(boolean hasLetter) {
        this.hasLetter = hasLetter;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    /**
     * 设置为只生成汉字
     * 
     * @return
     */
    public TextCaptchaCreator justChinese() {
        hasChinese = true;
        hasNumber = false;
        hasLetter = false;
        return this;
    }

}
